package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Classname OssServiceImpl
 * @Description TODO
 * @Date 2022/8/28 15:28
 * @Created by ZHL17
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileName = file.getOriginalFilename();
        fileName= UUID.randomUUID().toString().replaceAll("-","")+fileName;
        String dataPath=new DateTime().toString("yyyy/MM/dd");
        fileName=dataPath+"/"+fileName;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        // 创建PutObject请求。
        ossClient.putObject(bucketName, fileName, inputStream);
       // 关闭OSSClient。
        ossClient.shutdown();
        String url="https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;
    }
}
